"""
@author: Sergiy Tsymbalyuk
"""

import logging

from pylons import tmpl_context as c, request
from pylons.controllers.util import redirect
from pylons.i18n import lazy_ugettext as _
from formalchemy import Field

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import not_anonymous

from chowa.lib.site.forms import TabularFieldSet
from chowa.lib.site.messaging import send_system_message
from chowa.model.auth import User

from catalogue.lib.base import BaseController, render, Session
from catalogue.model.catalog import Section

log = logging.getLogger(__name__)

@ControllerProtector(not_anonymous())
class SettingsController(BaseController):
    def sections(self):
        user = request.environ.get('repoze.who.identity')['user']
        c.user = Session.query(User).get(user.id)
        
        fs = TabularFieldSet(c.user)
        fs.configure(include=[fs.sections], options=[fs.sections.label('')])
        if request.method == 'POST':
            fs.rebind(data=request.POST)
            fs.sync()
            Session.commit()
            # send_system_message(_('Saving configuration successful.'), user.id)
            return redirect(request.referer)
        c.form = fs.render()
        return render('/catalogue/settings/sections.html')
